package com.person.jiaiplan.config;


import com.person.jiaiplan.pojo.R;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @Description: 全局结果封装
 * @Author:
 */
@RestControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {


    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {

        return (AnnotatedElementUtils.hasAnnotation(returnType.getContainingClass(), ResponseBody.class) ||
                returnType.hasMethodAnnotation(ResponseBody.class));
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        // 提供一定的灵活度，如果body已经被包装了，就不进行包装
        if (body instanceof R) {
            return body;
        }

        /*下载文件跳过*/
        if (selectedContentType.includes(MediaType.APPLICATION_OCTET_STREAM)) {
            return body;
        }

        // 服务健康检查接口跳过
        String requestPath = request.getURI().getPath();
        if (requestPath.contains("/actuator/health")) {
            return body;
        }

       /* // 如果返回值是String类型，那就手动把Result对象转换成JSON字符串
        if (body instanceof String) {
            return JSONUtil.toJsonStr(R.ok(body));
        }*/

        return R.ok(body);
    }
}
